<template>
  <div class="template-manager-page">
    <el-card shadow="hover">
      <!-- 页面头部 -->
      <div slot="header" class="page-header">
        <div class="header-left">
          <h2 class="page-title">报告模板管理</h2>
          <el-tag type="info">项目: {{ currentProjectName }}</el-tag>
        </div>
        <div class="header-actions">
          <el-button
            type="primary"
            @click="createTemplate"
            icon="el-icon-plus"
          >
            新建模板
          </el-button>
          <el-button
            @click="importTemplate"
            icon="el-icon-upload2"
          >
            导入模板
          </el-button>
          <el-button
            @click="refresh"
            icon="el-icon-refresh"
          >
            刷新
          </el-button>
        </div>
      </div>

      <!-- 模板列表 -->
      <div class="template-list">
        <el-table
          :data="templateList"
          v-loading="loading"
          empty-text="暂无模板，点击新建模板开始创建"
          style="width: 100%"
        >
          <el-table-column prop="name" label="模板名称" min-width="150">
            <template #default="scope">
              <div class="template-name">
                <i :class="getTemplateIcon(scope.row.type)" class="template-icon"></i>
                <span>{{ scope.row.name }}</span>
                <el-tag
                  v-if="scope.row.isDefault"
                  size="mini"
                  type="success"
                  effect="dark"
                >
                  默认
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="type" label="模板类型" width="120">
            <template #default="scope">
              <el-tag :type="getTemplateTypeTag(scope.row.type)">
                {{ getTemplateTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="pageSize" label="页面尺寸" width="100">
            <template #default="scope">
              {{ scope.row.pageSize || 'A4' }}
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="createUser" label="创建人" width="120">
            <template #default="scope">
              {{ scope.row.createUser || '系统' }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <el-button
                type="text"
                size="mini"
                @click="editTemplate(scope.row)"
                icon="el-icon-edit"
              >
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="previewTemplate(scope.row)"
                icon="el-icon-view"
              >
                预览
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="setDefaultTemplate(scope.row)"
                :disabled="scope.row.isDefault"
                icon="el-icon-star-off"
              >
                设默认
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="duplicateTemplate(scope.row)"
                icon="el-icon-copy-document"
              >
                复制
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="deleteTemplate(scope.row)"
                style="color: #f56c6c"
                icon="el-icon-delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 模板设计器对话框 -->
    <el-dialog
      :title="designerDialog.title"
      :visible.sync="designerDialog.visible"
      fullscreen
      :close-on-click-modal="false"
      :before-close="handleDesignerClose"
    >
      <template-designer
        v-if="designerDialog.visible"
        :config="projectConfig"
        :initial-template="designerDialog.template"
        ref="templateDesigner"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDesignerClose">取消</el-button>
        <el-button type="primary" @click="saveTemplate" :loading="saving">
          保存模板
        </el-button>
        <el-button 
          v-if="designerDialog.mode === 'edit'" 
          @click="saveAsNewTemplate" 
          :loading="saving"
        >
          另存为
        </el-button>
      </div>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog
      :title="previewDialog.title"
      :visible.sync="previewDialog.visible"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <template-preview
        v-if="previewDialog.visible"
        :template="previewDialog.template"
        :test-data="previewDialog.testData"
        mode="preview"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialog.visible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="generateFromPreview"
          icon="el-icon-download"
        >
          生成文档
        </el-button>
      </div>
    </el-dialog>

    <!-- 导入模板对话框 -->
    <el-dialog
      title="导入模板"
      :visible.sync="importDialog.visible"
      width="600px"
      :close-on-click-modal="false"
    >
      <template-import
        v-if="importDialog.visible"
        @import="handleTemplateImport"
        @cancel="importDialog.visible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import TemplateDesigner from '@/components/template-designer/TemplateDesigner.vue'
import TemplatePreview from '@/components/template-designer/TemplatePreview.vue'
import TemplateImport from '@/components/template-designer/TemplateImport.vue'
// import { formatDate } from '@/utils/tools'

export default {
  name: 'TemplateManagerPage',
  components: {
    TemplateDesigner,
    TemplatePreview,
    TemplateImport
  },
  data() {
    return {
      // 模板列表数据
      templateList: [],
      loading: false,
      saving: false,
      
      // 分页配置
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      
      // 项目配置
      projectConfig: {},
      currentProjectName: '',
      
      // 对话框控制
      designerDialog: {
        visible: false,
        title: '',
        template: null,
        mode: 'create' // create, edit
      },
      
      previewDialog: {
        visible: false,
        title: '',
        template: null,
        testData: {}
      },
      
      importDialog: {
        visible: false
      }
    }
  },
  created() {
    this.loadProjectConfig()
    this.loadTemplates()
  },
  methods: {
    /**
     * 加载项目配置
     */
loadProjectConfig() {
  try {
    const savedConfig = localStorage.getItem('detectionConfig')
    if (savedConfig) {
      this.projectConfig = JSON.parse(savedConfig)
      console.log('项目配置加载成功:', this.projectConfig)
      this.currentProjectName = this.projectConfig.projectName || '当前项目'
      
      // 确保paramGroups存在
      if (!this.projectConfig.paramGroups) {
        this.projectConfig.paramGroups = []
      }
    } else {
      // 如果没有配置，使用默认结构
      this.projectConfig = {
        projectName: '默认项目',
        paramGroups: []
      }
    }
  } catch (error) {
    console.error('加载项目配置失败:', error)
    this.$message.error('加载项目配置失败')
    this.projectConfig = {
      projectName: '默认项目',
      paramGroups: []
    }
  }
},
    
    /**
     * 加载模板列表
     */
    async loadTemplates() {
      this.loading = true
      try {
        // 模拟API调用
        const mockTemplates = this.getMockTemplates()
        this.templateList = mockTemplates
        this.pagination.total = mockTemplates.length
      } catch (error) {
        console.error('加载模板列表失败:', error)
        this.$message.error('加载模板列表失败')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取模拟模板数据
     */
    getMockTemplates() {
      return [
        {
          id: 'TEMPLATE_001',
          name: '钢筋拉伸试验原始记录',
          type: 'record',
          pageSize: 'A4',
          isDefault: true,
          createTime: '2024-01-15T10:30:00',
          updateTime: '2024-01-20T14:25:00',
          createUser: '管理员'
        },
        {
          id: 'TEMPLATE_002',
          name: '混凝土抗压强度检测报告',
          type: 'report',
          pageSize: 'A4',
          isDefault: false,
          createTime: '2024-01-16T09:15:00',
          updateTime: '2024-01-18T16:40:00',
          createUser: '管理员'
        },
        {
          id: 'TEMPLATE_003',
          name: '综合检测报告模板',
          type: 'report',
          pageSize: 'A3',
          isDefault: false,
          createTime: '2024-01-10T11:20:00',
          updateTime: '2024-01-12T15:30:00',
          createUser: '测试员'
        }
      ]
    },
    
    /**
     * 获取模板图标
     */
    getTemplateIcon(type) {
      const iconMap = {
        record: 'el-icon-document',
        report: 'el-icon-files'
      }
      return iconMap[type] || 'el-icon-document'
    },
    
    /**
     * 获取模板类型标签样式
     */
    getTemplateTypeTag(type) {
      const tagMap = {
        record: 'primary',
        report: 'success'
      }
      return tagMap[type] || 'info'
    },
    
    /**
     * 获取模板类型文本
     */
    getTemplateTypeText(type) {
      const textMap = {
        record: '原始记录',
        report: '检测报告'
      }
      return textMap[type] || '未知类型'
    },
    
    /**
     * 格式化日期
     */
    formatDate(dateString) {
      return dateString
    },
    
    /**
     * 创建新模板
     */
    createTemplate() {
      this.designerDialog = {
        visible: true,
        title: '新建模板',
        template: null,
        mode: 'create'
      }
    },
    
    /**
     * 编辑模板
     */
    editTemplate(template) {
      // 模拟加载模板详情
      const templateDetail = this.getMockTemplateDetail(template.id)
      this.designerDialog = {
        visible: true,
        title: `编辑模板 - ${template.name}`,
        template: templateDetail,
        mode: 'edit'
      }
    },
    
    /**
     * 获取模拟模板详情
     */
    getMockTemplateDetail(templateId) {
      // 这里应该从API获取模板详情
      // 模拟返回模板配置
      return {
        id: templateId,
        name: '模板详情',
        type: 'record',
        pageSize: 'A4',
        components: [
          {
            id: 'COMP_001',
            type: 'header',
            position: { x: 0, y: 0, width: 794, height: 80 },
            content: {
              title: '钢筋拉伸试验原始记录',
              subtitle: '检测项目：钢筋母材力学性能',
              showBorder: true
            }
          },
          {
            id: 'COMP_002',
            type: 'text',
            position: { x: 50, y: 100, width: 200, height: 30 },
            content: {
              text: '样品编号：',
              fontSize: 12,
              fontWeight: 'normal'
            }
          }
        ]
      }
    },
    
    /**
     * 预览模板
     */
    previewTemplate(template) {
      // 加载测试数据
      const testData = this.loadTestData()
      this.previewDialog = {
        visible: true,
        title: `预览模板 - ${template.name}`,
        template: template,
        testData: testData
      }
    },
    
    /**
     * 加载测试数据
     */
    loadTestData() {
      try {
        const savedData = localStorage.getItem('testDataEntry')
        if (savedData) {
          return JSON.parse(savedData)
        }
        
        // 返回默认测试数据
        return {
          basicInfo: {
            sampleNo: 'TEST-2024-001'
          },
          groups: []
        }
      } catch (error) {
        console.error('加载测试数据失败:', error)
        return {}
      }
    },
    
    /**
     * 设置默认模板
     */
    async setDefaultTemplate(template) {
      try {
        await this.$confirm(
          `确定要将"${template.name}"设置为默认模板吗？`,
          '设置默认模板',
          {
            type: 'warning'
          }
        )
        
        // 调用API设置默认模板
        // await this.$api.template.setDefault(template.id)
        
        this.$message.success('默认模板设置成功')
        this.loadTemplates()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('设置默认模板失败:', error)
          this.$message.error('设置默认模板失败')
        }
      }
    },
    
    /**
     * 复制模板
     */
    async duplicateTemplate(template) {
      try {
        const newName = await this.$prompt(
          '请输入新模板名称',
          '复制模板',
          {
            inputValue: `${template.name}_复制`,
            inputValidator: (value) => {
              if (!value.trim()) {
                return '模板名称不能为空'
              }
              return true
            }
          }
        )
        console.log(newName)
        
        // 调用API复制模板
        // await this.$api.template.duplicate(template.id, newName.value)
        
        this.$message.success('模板复制成功')
        this.loadTemplates()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('复制模板失败:', error)
          this.$message.error('复制模板失败')
        }
      }
    },
    
    /**
     * 删除模板
     */
    async deleteTemplate(template) {
      try {
        await this.$confirm(
          `确定要删除模板"${template.name}"吗？此操作不可恢复。`,
          '删除模板',
          {
            type: 'warning',
            confirmButtonText: '确定删除',
            cancelButtonText: '取消'
          }
        )
        
        // 调用API删除模板
        // await this.$api.template.delete(template.id)
        
        this.$message.success('模板删除成功')
        this.loadTemplates()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除模板失败:', error)
          this.$message.error('删除模板失败')
        }
      }
    },
    
    /**
     * 导入模板
     */
    importTemplate() {
      this.importDialog.visible = true
    },
    
    /**
     * 处理模板导入
     */
    handleTemplateImport() {
      this.importDialog.visible = false
      this.$message.success('模板导入成功')
      this.loadTemplates()
    },
    
    /**
     * 刷新数据
     */
    refresh() {
      this.loadTemplates()
      this.$message.success('数据已刷新')
    },
    
    /**
     * 保存模板
     */
    async saveTemplate() {
      if (!this.$refs.templateDesigner) {
        this.$message.error('模板设计器未初始化')
        return
      }
      
      this.saving = true
      try {
        const templateData = this.$refs.templateDesigner.getTemplateData()
        console.log(templateData)

        // 验证模板数据
        if (!templateData.name || !templateData.name.trim()) {
          this.$message.error('请输入模板名称')
          return
        }
        
        // 调用API保存模板
        // await this.$api.template.save(templateData)
        
        this.$message.success('模板保存成功')
        this.designerDialog.visible = false
        this.loadTemplates()
      } catch (error) {
        console.error('保存模板失败:', error)
        this.$message.error('保存模板失败')
      } finally {
        this.saving = false
      }
    },
    
    /**
     * 另存为模板
     */
    async saveAsNewTemplate() {
      try {
        const newName = await this.$prompt(
          '请输入新模板名称',
          '另存为模板',
          {
            inputValue: `${this.designerDialog.template.name}_副本`,
            inputValidator: (value) => {
              if (!value.trim()) {
                return '模板名称不能为空'
              }
              return true
            }
          }
        )
        
        if (this.$refs.templateDesigner) {
          const templateData = this.$refs.templateDesigner.getTemplateData()
          templateData.name = newName.value
          templateData.id = null // 新建ID
          
          // 调用API保存为新模板
          // await this.$api.template.save(templateData)
          
          this.$message.success('模板另存为成功')
          this.designerDialog.visible = false
          this.loadTemplates()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('另存为模板失败:', error)
          this.$message.error('另存为模板失败')
        }
      }
    },
    
    /**
     * 处理设计器关闭
     */
    handleDesignerClose() {
      this.$confirm('确定要关闭吗？未保存的更改将会丢失。', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.designerDialog.visible = false
        })
        .catch(() => {})
    },
    
    /**
     * 从预览生成文档
     */
    generateFromPreview() {
      // 这里可以调用生成文档的API
      this.$message.success('文档生成请求已发送')
      this.previewDialog.visible = false
    },
    
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTemplates()
    },
    
    /**
     * 当前页改变
     */
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTemplates()
    }
  }
}
</script>

<style scoped>
.template-manager-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.template-list {
  margin: 20px 0;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-icon {
  color: #409eff;
  font-size: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .template-manager-page {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .template-manager-page {
    padding: 10px;
  }
}
</style>